// 该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import {nanoid} from 'nanoid'
// 应用Vuex插件
Vue.use(Vuex)

// 求和功能相关的配置
const countOptions = {
  namespaced: true,
  actions: {
    incrementOdd(context, value) {
      if(context.state.sum % 2) {
        context.commit('INCREMENT', value)
      }
    },
    incrementWait(context, value) {
      setTimeout(() => {
        context.commit('INCREMENT', value)
      }, 500)
    }
  },
  mutations: {
    INCREMENT(state, value) {
      console.log('mutations中的INCREMENT被调用了')
      state.sum += value
    },
    DECREMENT(state, value) {
      state.sum -= value
    }
  },
  state: {
    sum: 0
  },
  getters: {
    bigSum(state) {
      return state.sum * 10
    }
  }
}

// 人员管理相关的配置
const personOptions = {
  namespaced: true,
  actions: {
    addPersonWang(context, value) {
      if(value.name.indexOf('王') === 0) {
        context.commit('ADD_PERSON', value)
      } else {
        alert('添加的人必须姓王！')
      }
    },
    addPersonServer(context) {
      axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(response => {
        context.commit('ADD_PERSON', {id:nanoid(), name: response.data})
      }, error => {
        alert(error.message)
      })
    }
  },
  mutations: {
    ADD_PERSON(state, personObj) {
      state.personList.unshift(personObj)
    }
  },
  state: {
    personList: [
      {id: '001', name: '张三'}
    ]
  },
  getters: {
    firstPersonName(state) {
      return state.personList[0].name
    }
  }
}

// 创建并暴露store
export default new Vuex.Store({
  modules: {
    countAbout: countOptions,
    personAbout: personOptions
  }
  // actions,
  // mutations,
  // state,
  // getters
})
